package cn.iocoder.yudao.module.vote.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.iocoder.yudao.module.vote.constants.Const;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * @description:
 * @author: moving
 * @date: 2022/11/10 17:01
 */
public class AesUtil {
    /**
     * 16字节
     */
    private static final String ENCODE_KEY = "QWERBGH9HNJ123d5";
    private static final String IV_KEY = "0000000000000000";

    public static void main(String[] args) {
        String encryptData = encrypt("zdm321123.");
        System.out.println("加密：" + encryptData);
        String decryptData = decrypt(encryptData);
        System.out.println("解密：" + decryptData);
        String params = StrUtil.format(Const.VOTE_QRCODE_PARAMS,1,true,false);
        String encryptParams = AesUtil.encrypt(params);
        String url = StrUtil.format(Const.VOTE_QRCODE_URL, AesUtil.encrypt(params));
        System.out.println(url);
        System.out.println(AesUtil.decrypt(encryptParams));
    }

    public static String encrypt(String data){
        return encryptFromString(data,Mode.CBC, Padding.ZeroPadding);
    }

    public static String decrypt(String data) {
        return decryptFromString(data,Mode.CBC, Padding.ZeroPadding);
    }


    public static String encryptFromString(String data, Mode mode, Padding padding) {
        AES aes;
        if (Mode.CBC == mode) {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
                    new IvParameterSpec(IV_KEY.getBytes()));
        } else {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
        }
        return aes.encryptHex(data, StandardCharsets.UTF_8).toUpperCase(Locale.ROOT);
    }

    public static String decryptFromString(String data, Mode mode, Padding padding) {
        AES aes;
        if (Mode.CBC == mode) {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
                    new IvParameterSpec(IV_KEY.getBytes()));
        } else {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
        }
        return aes.decryptStr(data, StandardCharsets.UTF_8);
    }

}
